package config

import (
	"invitation/internal/model"
	"time"

	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
)

type DBLoader interface {
	Load()
	DB() *gorm.DB
}

type sqliteLoader struct {
	dbFilePath string
	db         *gorm.DB
}

func NewSqliteDBLoader(dbFilePath string) DBLoader {
	return &sqliteLoader{
		dbFilePath: dbFilePath,
	}
}
func (sl *sqliteLoader) Load() {

	// 添加SQLite特定参数
	dsn := sl.dbFilePath + "?_foreign_keys=on&_journal_mode=WAL"
	db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
	if err != nil {
		// 生产环境中应该返回错误而不是panic
		panic(err)
	}

	sqlDB, err := db.DB()
	if err != nil {
		panic(err)
	}

	// SQLite通常不需要太多连接
	sqlDB.SetMaxIdleConns(5)
	sqlDB.SetMaxOpenConns(20)
	sqlDB.SetConnMaxLifetime(time.Hour)

	sl.db = db
	if err := sl.initDB(); err != nil {
		panic(err)
	}
}

func (sl *sqliteLoader) DB() *gorm.DB {
	return sl.db
}

func (sl *sqliteLoader) initDB() error {
	if err := sl.db.AutoMigrate(&model.GameInfo{}); err != nil {
		return err
	}

	if err := sl.db.AutoMigrate(&model.GameIntroduction{}); err != nil {
		return err
	}
	if err := sl.db.AutoMigrate(&model.GameTheory{}); err != nil {
		return err
	}
	if err := sl.db.AutoMigrate(&model.FirstTimeTeacherInfo{}); err != nil {
		return err
	}
	if err := sl.db.AutoMigrate(&model.FirstTimePostport{}); err != nil {
		return err
	}
	return nil
}
